<?php
class CategoriesController 
	extends Zend_Controller_Action 
{
	public function indexAction() 
	{

		$pagination = $this->getHelper('Pagination');
		
		$params = array();
		
		$mapper = Vs_Factory::mapper( 'Category' );
		
		$categories = $mapper->getByParams( $params, $pagination->offset, $pagination->limit, $pagination->order );
		$totalItems = $mapper->countByParams( $params );
		
		$pagination->setItemsCount( $totalItems );
		
		$this->view->categories = $categories;
		
		if ( $this->getRequest()->isXmlHttpRequest()){
			$this->_helper->layout->disableLayout();
			$this->render('categories');
		} 
		
	}
	
	public function createAction() 
	{
		$form = new Adm_Form_Category();
		$form->setAction(
			$this->_helper->url('create')
		);
		
		if($this->getRequest()->isPost()){
			
			$data = $this->getRequest()->getPost();
		
			if ( $form->isValid($data)) {
				
				$mapper = Vs_Factory::mapper( 'Category' );
				
				$category = new Vs_Category ($data);
				$mapper->save( $category );				
			
				$this->getHelper('MyFlashMessenger')->addSuccess( "La cetegoría fue creada" );
				
				return $this->_helper->Redirector('index');
				
			} else {			
				$form->populate($data);			
			}	
		}				
		
		$this->view->form = $form;
		$this->render('create');	
	}
	
	public function deleteAction() 
	{
		$ids = explode("-", $this->getRequest()->getParam('ids'));
		
		foreach ($ids as $categoryId){
			
			try {
				$mapper = Vs_Factory::mapper( 'Category' );
				$category = $mapper->getById( $categoryId );
				$mapper->delete( $category );
				
				$this->getHelper('MyFlashMessenger')->addSuccess( "La categoria {$categoryId} fue eliminada");
				
			}catch (Vs_Exception $e){
			
				$this->getHelper('MyFlashMessenger')->addError( $e->getMessage() );
			}
		} 
		
		return $this->_helper->Redirector('index');
	}
	
	public function updateAction() 
	{
		$categoryId = (int) $this->_getParam('categoryId');
		$mapper = Vs_Factory::mapper( 'Category' );
		
		try{
			$category = $mapper->getById( $categoryId );
		} catch (Vs_Exception $e){		
			$this->getHelper('MyFlashMessenger')->addError( $e->getMessage() );
			return $this->_helper->Redirector('index');
		}
		
		$form = new Adm_Form_Category(array('exclude' =>$category->name));
		$form->setAction(
			$this->_helper->url('update', null, null, array('categoryId'=>$categoryId))
		);
		
		if($this->getRequest()->isPost()){
			
			$data = $this->getRequest()->getPost();
		
			if ( $form->isValid($data)) {

				$data['categoryId'] = $categoryId;
				$category = new Vs_Category ($data);
				$mapper->save( $category );				
				$this->getHelper('MyFlashMessenger')->addSuccess("La categoria {$categoryId} fue modificada");
				return $this->_helper->Redirector('index');
				
			} else {			
				$form->populate($data);			
			}	
		}  else {			
			$form->populate( (array) $category );			
		}					
		
		$this->view->form = $form;
		$this->render('create');	
	}
}